﻿using Microsoft.AspNetCore.Mvc;
using News__mvc.Models;
using News__mvc.Models.Database;
using System;
using System.Linq;

namespace new_mvc.Controllers
{
    public class NewsController : Controller
    {
        private readonly NewsContext _db;
        public NewsController(NewsContext db)
        {
            _db = db;
        }

        [Route("/")]
        [Route("/Index.html")]
        public IActionResult Index(string word,int nid = 0,int pageid=0)
        {
            //查询所有数据
            var news = _db.News.ToList();
            var cate = _db.Categories.ToList();
            var page = _db.Pages.ToList();

            if (pageid > 0)
            {
                //如果页数Id大于0 跳过(pageid - 1) * 4行数据 取4行
                news = _db.News.Skip((pageid - 1) * 4).Take(4).ToList();
            }
            if (nid > 0)
            {
                //如果nid>0 查询数据库条件cateID=nid的数据
                news = news.Where(x => x.CateId == nid).ToList();
            }
            if (word != null)
            {
                //模糊查询数据库Newsc=word的数据
                news= _db.News.Where(x => x.Newsc.Contains(word)).ToList();
            }
            //把数据传到视图
            ViewData["cate"] = cate;
            ViewData["news"] = news;
            ViewData["page"] = page;
            ViewData["nid"] = nid;
            ViewData["pageid"] = pageid;
            return View();
        }

        [Route("/detail.html")]
        public IActionResult Detail(int id)
        {
            var news = _db.News.FirstOrDefault(x => x.Id == id);
            ViewData["news"] = news;
            return View();
        }
    }
}
